<template>
  <div class="index-box d-flex" ref="index">
  			<div class="leftBox" :style="{'width': leftTreeShow?'200px':'0px'}">
		  			<div class="tree-box">
		          <el-tree :data="treeList" node-key="operationId" ref="tree"  current-node-key="" :props="defaultProps" default-expand-all :expand-on-click-node="false" @node-click="handleNodeClick"></el-tree>
		        </div>
		  	</div>
		  	<div class="rightBox">
		  			<div class="main-box" >
		          <div class="search" ref="search">
		            <el-form :inline="true" :model="searchForm" size="small" ref="searchForm" @submit.native.prevent
		              class="demo-form-inline" id="searchBox">
		              <el-form-item prop="goodsCode">
		                  <el-input v-model="searchForm.goodsCode" clearable placeholder="请输入商品编号"></el-input>
		              </el-form-item>
		              <el-form-item prop="goodsName">
		                  <el-input v-model="searchForm.goodsName" clearable placeholder="请输入商品名称"></el-input>
		              </el-form-item>
                  <el-form-item prop="storeName">
                      <el-input v-model="searchForm.storeName" clearable placeholder="请输入商家门店名称"></el-input>
                  </el-form-item>
                  <el-form-item prop="auditUserName">
                    <el-input v-model="searchForm.auditUserName" clearable placeholder="请输入审核人信息"></el-input>
                  </el-form-item>
                  <el-form-item prop="storeCategoryId">
                   <treeselect
                     v-model="searchForm.storeCategoryId"
                     :options="storeListOptions"
                     :normalizer="normalizer"
                     :show-count="true"
                     placeholder="商家类型"
                   />
                  </el-form-item>
                  <el-form-item prop="goodsState">
                    <el-select filterable clearable v-model="searchForm.goodsState" placeholder="全部上/下架">
                      <el-option label="已上架" value="1" ></el-option>
                      <el-option label="已下架" value="2" ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item prop="goodsType">
                      <el-select v-model="searchForm.goodsType" placeholder="所属商品专区">
                          <el-option label="好礼" value="1"></el-option>
                          <el-option label="好店" value="2"></el-option>
                      </el-select>
                  </el-form-item>
                  <el-form-item prop="time">
                    <el-date-picker v-model="time" type="daterange" align="right" unlink-panels range-separator="至"
                      start-placeholder="添加开始日期" end-placeholder="添加结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                      :picker-options="pickerOptions">
                    </el-date-picker>
                  </el-form-item>
		              <el-form-item class="clearfix">
		                <el-button type="primary" @click="handleSearch()" icon="el-icon-search">查询</el-button>
		                <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
		              </el-form-item>
		            </el-form>
		          </div>
		          <div class="actionBtn" ref="actionBtn">
		            <div class="actionBtnLeft d-flex align-center">
                  <MyLeftTreeRetract :leftTreeShow.sync="leftTreeShow"></MyLeftTreeRetract>
                  <el-radio-group v-model="searchForm.levelId" size="small" style="margin-right: 15px;" @change="handleSearch()">
                    <el-radio-button label="" >全部</el-radio-button>
                    <el-radio-button :label="item.levelId" v-for="item in levelList">{{item.name}}</el-radio-button>
                  </el-radio-group>
		              <el-button type="primary" @click="handleAdd()" size="small"  icon="el-icon-plus"  v-has="'shop:shopOperationNow:add'">添加商品</el-button>
		            </div>
		            <div class="actionBtnRight">
		                <MyRefresh/>
		            </div>
		          </div>
		          <div class="table" ref="table">
		            <el-table :data="dataList" style="width: 100%;"  border stripe :height="tableHeight" v-loading="loading">
		              <el-table-column prop="goodsCode" label="商品编号" v-if="!hideTableColumn.includes('number')" width="120"></el-table-column>
		              <el-table-column prop="name"  label="商品" v-if="!hideTableColumn.includes('img')" min-width="250">
		                <template #default="scope">
		                  <div class="goodsBox">
		                    <div class="img">
		                      <el-image :src="scope.row.goodsImage" fit="fill" v-image-preview="scope.row.goodsImage"></el-image>
		                    </div>
		                    <div class="goodsRight">
		                      <div class="goodsName ellipsis-item">{{scope.row.goodsName}}</div>
		                      <div class="goodsLabel">
		                        <MyTableTag :tagList="scope.row.tagNames"/>
		                      </div>
		                    </div>
		                  </div>
		                </template>
		              </el-table-column>
		              <el-table-column prop="skuStocksList[0].originalPrice" label="原价(元)" v-if="!hideTableColumn.includes('original')"  align="center" width="100"></el-table-column>
                  <el-table-column prop="skuStocksList[0].costPrice" label="供货价(元)" v-if="!hideTableColumn.includes('original')"  align="center" width="100"></el-table-column>
		              <el-table-column prop="skuStocksList[0].salePrice" label="平台售价(元)" v-if="!hideTableColumn.includes('retail')"  align="center"  width="120"></el-table-column>
		              <el-table-column prop="couponPrice" label="消费券抵扣(元)" v-if="!hideTableColumn.includes('retail')"  align="center"  width="120">
                    <template slot-scope="scope">
                      <span>{{scope.row.goodsType=='1'?scope.row.couponPrice:'0'}}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="goodsType" label="所属商品专区" v-if="!hideTableColumn.includes('goodsType')"  align="center"  width="120">
                    <template slot-scope="scope">
                      <span v-if="scope.row.goodsType=='1'">好礼</span>
                      <span v-else-if="scope.row.goodsType=='2'">好店</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="storeName" label="商家门店名称(元)" v-if="!hideTableColumn.includes('retail')"  align="center"  width="120"></el-table-column>
                  <el-table-column prop="storeTypeName" label="商家类型" v-if="!hideTableColumn.includes('retail')"  align="center"  width="120"></el-table-column>
                  <el-table-column prop="levelName" label="会员等级" v-if="!hideTableColumn.includes('retail')"  align="center"  width="120"></el-table-column>
                   <el-table-column prop="auditUserName" label="审核人信息"  align="center"  width="120"></el-table-column>
                  <el-table-column prop="name" label="上/下架" v-if="!hideTableColumn.includes('upDownStatus')" align="center" width="120">
                    <template #default="scope">
                        <span>{{scope.row.goodsState=='2'?'已下架':'已上架'}}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="createTime" label="添加时间" v-if="!hideTableColumn.includes('createTime')"  align="center"  width="120">
                    <template slot-scope="scope">
                     <span>{{ parseTime(scope.row.createTime) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="排序" align="center" prop="createTime" width="170"  v-if="!hideTableColumn.includes('sort')">
                    <template slot-scope="scope">
                      <div v-has="'shop:shopOperationNow:sort'">
                        <el-button size="mini" @click="handleTop(scope.row,scope.$index)">置顶</el-button>
                        <el-button icon="el-icon-top" circle size="mini" @click="hanleSort(scope.row,scope.$index,'1')" :disabled="scope.$index=='0'"></el-button>
                        <el-button icon="el-icon-bottom" circle size="mini" @click="hanleSort(scope.row,scope.$index,'2')" :disabled="scope.$index==searchForm.pageSize-1"></el-button>
                      </div>
                    </template>
                  </el-table-column>
		              <el-table-column prop="name" label="操作"  align="center" width="130" fixed="right">
		                <template #default="scope">
		                 <div class="verticalBtn">
		                      <el-button
		                        size="medium"
		                        type="text"
		                        icon="el-icon-picture-outline-round"
		                        @click="handleLook(scope.row)"
		                      >商品详情</el-button>

                          <el-button
                            size="medium"
                            type="text"
                            icon="el-icon-delete-solid"
                             v-has="'shop:shopOperationNow:delt'"
                            @click="handleDelt(scope.row)"
                          >移除</el-button>
		                  </div>
		                </template>
		              </el-table-column>
		            </el-table>
		          </div>
		          <div class="page" ref="page">
		            <MyPagination
		               :total="total"
		               :page.sync="searchForm.pageNum"
		               :limit.sync="searchForm.pageSize"
		               @pagination="dataInfo"
		             />
		          </div>
		        </div>
  	</div>
  <!-- 选择商品类型 -->
  <el-dialog title="商品专区" width="500px" v-dialogDrag :close-on-click-modal="false" :visible.sync="shopTypeVisible" @close="shopTypeVisible = false">
     <div class="shopOperationBox">
       <div>请选择所属商品专区:</div>

         <el-radio-group v-model="shopOperationForm.goodsType" class="d-flex groupBox" style="flex-wrap: inherit;padding:0 100px">
           <el-radio label="1" >好礼</el-radio>
           <el-radio label="2" >好店</el-radio>
         </el-radio-group>
     </div>
     <div slot="footer" class="dialog-footer">
       <el-button @click="shopTypeVisible = false" size="small">取 消</el-button>
       <el-button type="primary" @click="handleSureGoodsType()" size="small" :loading="userLoading">确 定</el-button>
     </div>
   </el-dialog>

   <!--	选择商品	-->
   <el-dialog title="选择商品" :visible.sync="productsDialogVisible" :close-on-click-modal="false" v-dialogDrag>
      <el-dialog
        width="30%"
        title="请上传Banner"
        :visible.sync="innerVisible"
        append-to-body>
        <div class="content flex1">
          <MyUpImg :imagePreview='bannerImg' :imageSource='bannerImg' @change="changBanner1" size="700"></MyUpImg>
          <p class="red">图片规格为：宽 700px、高230px、尺寸不能超过10mb</p>
          <p >备注：上传Banner图时，一定要按照图片的规格大小和图片展现的方式制作，您可右击下载 图片进行参考，上传的图若造成平台负面影响，仟店平台会下架您的商品并追究相关责任。</p>

        </div>
        <div slot="footer" class="dialog-footer">
        	<el-button size="small" @click="innerVisible = false">取消</el-button>
          <el-button size="small" @click="submitYesApply" type="primary" :loading="loading">确定</el-button>
        </div>
      </el-dialog>
     <div class="tableBox d-flex">
       <div class="leftBox" style="width: 160px;height:700px" v-if="shopOperationForm.goodsType=='1'">
           <el-tree :data="shopTypeList" node-key="categoryId" ref="tree"  current-node-key="" :props="defaultProps" default-expand-all :expand-on-click-node="false" @node-click="handleShopTypeNodeClick"></el-tree>
       </div>
       <div class="rightBox" style="flex:1">
         <div class="search-box">
             <el-form :inline="true" :model="shopDialog" size="small" ref="shopDialog" @submit.native.prevent
               class="demo-form-inline d-flex " id="searchBox"  style="flex-wrap: wrap;">
               <el-form-item prop="goodsCode" style="width:200px">
                   <el-input v-model="shopDialog.goodsCode" clearable placeholder="商品编号"></el-input>
               </el-form-item>
               <el-form-item prop="name" style="width:200px">
                   <el-input v-model="shopDialog.goodsName" clearable placeholder="商品名称"></el-input>
               </el-form-item>
               <el-form-item class="clearfix">
                 <el-button type="primary" @click="handleShopSearch()" icon="el-icon-search">搜索</el-button>
               </el-form-item>
             </el-form>
           </div>
         <el-row :gutter="20">
           <el-col :span="6" v-for="(item, index) in shopDialogList" :key="index">
           	<el-card :body-style="{ padding: '0px' }"  style="margin-bottom: 10px;">
           		<img :src="item.goodsImage" height="185" style="margin: auto;display: block;">
           		<div style="padding: 14px;">
           			<p style="margin: 0px;" class="ellipsis-item" :title="item.goodsName">{{item.goodsName}}</p>
                <p style="margin: 0px;" class="ellipsis-item" :title="item.goodsCode">({{item.goodsCode}})</p>
           			<el-button size="small" @click="checkShop(item)" :disabled="btnLoading">选择</el-button>
           		</div>
           	</el-card>
           </el-col>
           <el-empty :image-size="200" v-if="!shopDialogList.length"></el-empty>

         </el-row>
         <MyPagination
            v-if="shopDialogList.length"
           :total="shopDialog.total"
           :page.sync="shopDialog.pageNum"
           :limit.sync="shopDialog.pageSize"
           @pagination="getShopList"
         />
       </div>
     </div>


   	<div slot="footer" class="dialog-footer">
   		<el-button size="small" @click="productsDialogVisible = false">取 消</el-button>
   	</div>
   </el-dialog>
   <!--	选择商品	-->

  </div>
</template>

<script>
  import common from '@/api/api';
  import { addGoodsOperationGroup,getGoodsColumnList,getOperationGoodsLists,getOperationGroupList,removeOperationGroupById,getCategoryGoodsList,goodsQuerylist,operationPopularGoodsSortUp,operationPopularGoodsUpTop } from '@/api/getData';
  import option from '../../common/option.js';
  import { regionData,CodeToText } from 'element-china-area-data';
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  export default {
    components: { Treeselect },
    data() {
      return {
        loading: false,
        userLoading: false,
        btnLoading: false,
        innerVisible:false,
        leftTreeShow: true,
        shopTypeList:[],//商家类型列表
        auditList:[],
        levelList:[],
        tableColumn:[],
        hideTableColumn:[],/*自定义表格列需要隐藏的*/
        tableColumnType:'staffManagement',/*自定义表格列类型传参*/
        time:[],
        searchForm: {
          operationId:'',
          goodsCode:"",
          goodsName:'',
          goodsState:'',
          storeCategoryId:undefined,
          storeName:'',
          levelId:'',
          goodsType:'',
          auditUserName:'',

          pageNum: 1,
          pageSize: 20,
          orderByColumn:'',
          isAsc:'',
        },
        treeList: [{operationId: "",name: "商品运营组",children: []}],
        storeListOptions:[],//商家门店
        tableHeight:400,//table 高度
        dataList:[],
        total: 0,
        defaultProps: {
           children: 'children',
           label: 'name'
        },
        statusRow:{},
        shopOperationForm:{
          goodsType:'',
          goodsId:'',
          operationId:'',
          imagePath:'',
          relationId:'',
          storeId:'',
        },
        shopOperationVisible:false,
        operationList:[],

        bannerImg:'',
        shopDialog:{
          goodsCode:"",
          goodsName:'',
          categoryId: '',
          storeName:'',
          parentCategoryId:'',
          total:0,
          pageNum:1,
          pageSize:10,
        },
        shopDialogList:[],
        productsDialogVisible:false,

        shopTypeVisible:false
      }
    },
    computed: {
      pickerOptions: () => {
        return option.pickerOptions;
      }
    },
    mounted() {
      this.getSelect();
      this.dataInfo();
      this.$nextTick(() => {
          this.tableHeight = this.$refs.index.offsetHeight - this.$refs.search.offsetHeight - this.$refs.actionBtn.offsetHeight - this.$refs.page.offsetHeight - 55;
      })
    },
    methods: {
      async checkShop(item){/*选中商品*/
      try {
          this.statusRow = item;
           this.loading = true;
           this.btnLoading = true;
           const result = await addGoodsOperationGroup({goodsId:this.statusRow.goodsId,operationId:this.searchForm.operationId,storeId:this.statusRow.storeId,goodsType:this.shopOperationForm.goodsType });
           if (result.code == 200) {
              this.$message.success('成功');
             this.productsDialogVisible = false;
             this.innerVisible = false
             this.dataInfo();
           } else {
             this.$message.error(result.msg);
           }
           this.loading = false;
           this.btnLoading = false;
         } catch (err) {
           console.log(err)
         }
      },
      submitYesApply(){/*好礼商品提交*/
        if(this.searchForm.operationId=='1498922467067502594' && (!this.bannerImg)){
          this.$message.error('请上传banner!');
        }else{
          this.submitApply();
        }
      },
      async submitApply(){
         try {
            this.loading = true;
            const result = await addOperationGroup({goodsId:this.statusRow.goodsId,operationId:this.searchForm.operationId,storeId:this.statusRow.storeId,bannerImg:this.bannerImg });
            if (result.code == 200) {
               this.$message.success('成功');
              this.productsDialogVisible = false;
              this.innerVisible = false
              this.dataInfo();
            } else {
              this.$message.error(result.msg);
            }
            this.loading = false;
        } catch (err) {
          console.log(err)
        }
      },
      async dataInfo() {
        try {
           let data = this.addDateRange(this.searchForm, this.time, 'startTime', 'endTime');
          this.loading = true;
          const result = await getOperationGoodsLists(data);
          if (result.code == 200) {
            this.total = result.total;
            this.dataList = result.rows;
          } else {
            this.$message.error(result.msg);
          }
          this.loading = false;
        } catch (err) {
          this.loading = false;
          console.log(err)
        }
      },
      changBanner(path){
        this.shopOperationForm.imagePath = path;
      },
      changBanner1(path){
        this.bannerImg = path;
      },
      handleTop(row,index){
        this.$confirm(`您确定要置顶该商品吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let data = {
            relationId : row.relationId
          }
          operationPopularGoodsUpTop(data).then((result)=>{
          		if (result.code == 200) {
                this.$message.success(result.msg);
                this.searchForm.pageNum = 1;
                this.dataInfo();
              } else {
                this.$message.error(result.msg);
              }
          })
         })
      },
      handleDelt(row){
        this.$confirm(`您确定要移除该商品吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let data = {
            relationId : row.relationId
          }
          removeOperationGroupById(data).then((result)=>{
          		if (result.code == 200) {
                this.$message.success(result.msg);
                this.dataInfo();
              } else {
                this.$message.error(result.msg);
              }
          })
         })
      },
      hanleSort(row,index,type){
        let indexs = (type=='1'?index-1:index+1)
        let data = {
          relationId:row.relationId,
          changeRelationId:this.dataList[indexs].relationId
        }
        operationPopularGoodsSortUp(data).then((result)=>{
        		if (result.code == 200) {
              this.$message.success(result.msg);
              this.dataInfo();
            } else {
              this.$message.error(result.msg);
            }
        })
      },
      /** 转换菜单数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.categoryId,
          label: node.name,
          children: node.children
        };
      },
      submitshopOperation(){
        if(!this.shopOperationForm.operationId){
          this.$message.error('请选中其中一个')
         }else if(this.shopOperationForm.operationId=='1498922467067502594' && (!this.shopOperationForm.imagePath)){
          // }else if(!this.shopOperationForm.bannerImage){
          this.$message.error('请上传Banner')
        }else{
          this.userLoading = true;
          updateOperationGoods(this.shopOperationForm).then(res=>{
             if (res.code == 200) {
               this.$message.success(res.msg);
               this.shopOperationVisible = false;
               this.dataInfo();
             } else {
               this.$message.error(res.msg);
             }
             this.userLoading = false;
          });
        }

      },
      getSelect(){
       getOperationGroupList().then(res=>{
          this.treeList[0].children = res.data;
          //this.operationList = res.list;
        })
        this.getCategoryDetails({categoryKey:'member_level_category'}).then(res=>{
          this.levelList = res.data;
        })
        this.getSelectList('goods_audit_status').then(res=>{ this.auditList = res.data; })
        this.getCategoryDetails({categoryKey:'stores_category'})/* 商家类型*/
        .then(res=>{
          this.storeListOptions = res.data;
        })
      },


      handleLook(row){
        this.$router.push({path:'/shop/shopDetails',query:{goodsId:row.goodsId,goodsType:row.goodsType}});
      },

      handleSureGoodsType(){
        if(!this.shopOperationForm.goodsType){
           this.$message.error('请选择所属商品专区')
        }else{
          this.shopTypeVisible = false;
          this.productsDialogVisible = true;
          this.getCategoryDetails({categoryKey:'product_category'})
          .then(res=>{
            this.shopTypeList = [{
              categoryId:'',
              children: res.data,
              name: "商品分类",
            }];
          })
          this.getShopList();
        }
      },
      handleAdd(){
        if(!this.searchForm.operationId){
          this.$message.error('请先选中左边的运营组')
        }else{
            this.shopOperationForm.goodsType = '';
            this.shopTypeVisible = true;

        }
      },
      handleShopSearch(){
        this.shopDialog.pageNum = 1;
         this.getShopList();
      },
      async getShopList(){
        try {
          this.dialogLoading = true;
          let result = '';
          if(this.shopOperationForm.goodsType=='1'){
            result = await getCategoryGoodsList(this.shopDialog);
          }else{
            let data = {
              goodsCode:this.shopDialog.goodsCode,
              goodsName:this.shopDialog.goodsName,
              goodsCategoryId:this.shopDialog.categoryId,
              storeName:this.shopDialog.storeName,
              parentCategoryId:this.shopDialog.parentCategoryId,
              pageNum:this.shopDialog.pageNum,
              pageSize:this.shopDialog.pageSize,
            }
            result = await getGoodsColumnList(data);
          }
          if (result.code == 200) {
            this.shopDialog.total = result.total;
            this.shopDialogList = result.rows;
          } else {
            this.$message.error(result.msg);
          }
          this.dialogLoading = false;
        } catch (err) {
          this.dialogLoading = false;
          console.log(err)
        }
      },
      normalizer2(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.categoryId,
          label: node.name,
          children: node.children
        };
      },
      resetQuery() {
        this.time = [];
        this.resetForm("searchForm");
        this.dataInfo();
      },

      handleSearch() {
        this.searchForm.pageNum = 1;
        this.dataInfo();
      },
      /* 左边运营组树节点点击事件 */
      handleNodeClick(data){
        this.searchForm.operationId =  data.operationId;
        this.handleSearch();
      },
      /** 弹框商品类型树节点点击事件 **/
      handleShopTypeNodeClick(data){
        this.shopDialog.categoryId =  data.categoryId;
        this.shopDialog.parentCategoryId = data.parentId;
        this.getShopList();
      },

    }
  }
</script>

<style scoped lang="scss">
  .groupBox /deep/ .el-radio{
    display: flex;
        justify-content: center;
  }
  .shopOperationBox /deep/ .el-radio-group{
    display: flex;
    flex-wrap: wrap;
  }
  .shopOperationBox /deep/ .el-radio-group .el-radio{
    width: 100%;
    padding:10px 0;
  }
  .tableDialog /deep/ .el-table__header-wrapper  .el-checkbox{//找到表头那一行，然后把里面的复选框隐藏掉
    display:none
  }
	.searchAddress /deep/ .el-input{
		width:220px!important;
	}
  .tagBox{
    cursor: pointer;
  }
  .activeCheckedBox{
      border-top: 1px solid #ddd;
      padding: 10px;
      height: 52px;
  }
  .index-box{
    padding:0px!important;
    margin-left:0px;
  }
  .tree-box /deep/ .el-tree-node{
     background: #D8E4DD;
  }
  .tree-box> /deep/ .el-tree>.el-tree-node{
    padding:3px;
  }
  .tree-box> /deep/ .el-tree .is-current{
    background:#fff;
  }
  .table-box{
    padding:15px
  }
  .down{
    color: #909399;
    cursor: pointer;
    text-decoration:underline;
  }
  .down:hover{
    color: #a6a9ad;
  }
  .up{
    color:#61997A;
    cursor: pointer;
    text-decoration:underline;
  }
  .up:hover{
    color:#81ad95;
  }
  .treeTitle{
    color: #606266;
    font-size: 15px;
    font-weight: bold;
    margin:20px 20px 0 20px;
  }
</style>
